import { provide, ref, inject } from 'vue';
import i18n, { loadLanguageAsync } from '@src/locales';
import router from '@src/router';

/**
 * provide传递的语言信息
 * @param key 自定义传递的标识
 */
export function useLocaleProvide(key: string) {
  const locale = ref(i18n.locale);
  provide(key, locale);

  function changeLocale(lan = i18n.locale) {
    locale.value = lan;
  }

  function setFormPreviewLocale(lan:string){
    locale.value = lan
  }

  return {
    locale,
    changeLocale,
    setFormPreviewLocale
  };
}

/**
 * inject 接收provide传递的语言信息
 * @param key 自定义接收传递的标识
 */
export function useLocaleInject(key: string) {
  const locale = inject(key, i18n.locale);

  return {
    locale,
  };
}
/**
 * 切换系统内的语言
 * @param locale
 */
export async function setLocale(locale: string) {
  try {
    await loadLanguageAsync(locale);
    router.push('/reload');
  } catch (error) {
    console.error('切换语言', error);
  }
}

export function useLoadLanguage() {
  return {
    setLocale,
  };
}
